package com.spsoft.vatoutinv.service.vmsepsInformation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spsoft.core.constants.CommonConstants;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.core.model.Result;
import com.spsoft.core.utils.BeanUtils;
import com.spsoft.core.utils.CollectionUtils;
import com.spsoft.core.utils.SecurityUtils;
import com.spsoft.core.utils.StringUtil;
import com.spsoft.vatoutinv.constants.CommonConstant;
import com.spsoft.vatoutinv.entity.vmsavalibletaxrate.VmsAvalibleTaxRate;
import com.spsoft.vatoutinv.entity.vmsclassifycode.VmsClassifyCode;
import com.spsoft.vatoutinv.entity.vmsdifferentialcode.VmsDifferentialCode;
import com.spsoft.vatoutinv.entity.vmsepsInformation.VmsEpsInformation;
import com.spsoft.vatoutinv.mapper.VmsEpsInformationMapper;
import com.spsoft.vatoutinv.model.dto.vmsepsInformation.VmsEpsCheckDto;
import com.spsoft.vatoutinv.model.dto.vmsepsInformation.VmsEpsClassifyCodePageDto;
import com.spsoft.vatoutinv.model.dto.vmsepsInformation.VmsEpsInformationDto;
import com.spsoft.vatoutinv.model.dto.vmsepsInformation.VmsEpsInformationQueryDto;
import com.spsoft.vatoutinv.model.vo.vmsclassifycode.VmsClassifyCodeForEpsPageVOList;
import com.spsoft.vatoutinv.model.vo.vmsepsInformation.VmsEpsInformationVo;
import com.spsoft.vatoutinv.model.vo.vmsepsInformation.VmsEpsSlVo;
import com.spsoft.vatoutinv.model.vo.vmsepsInformation.VmsEpsUpdateInformationVo;
import com.spsoft.vatoutinv.service.translate.impl.DictTranslate;
import com.spsoft.vatoutinv.service.vmsavalibletaxrate.VmsAvalibleTaxRateService;
import com.spsoft.vatoutinv.service.vmsclassifycode.VmsClassifyCodeService;
import com.spsoft.vatoutinv.service.vmsdifferentialcode.VmsDifferentialCodeService;
import com.spsoft.vatoutinv.service.vmsepsInformation.VmsEpsInformationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author liwm
 * @Desc 企业商品及服务信息管理表;企业商品及服务信息管理表 SEQ_VMS_EPS_INFORMATION
 * Enterprise Product and Service Information Management(VmsEpsInformation)表服务实现类
 * @Date 2024-01-08 13:24:31
 */
@Slf4j
@RequiredArgsConstructor
@Service("vmsEpsInformationService")
public class VmsEpsInformationServiceImpl extends ServiceImpl<VmsEpsInformationMapper, VmsEpsInformation> implements VmsEpsInformationService {

    private final VmsClassifyCodeService classifyCodeService;
    private final VmsDifferentialCodeService differentialCodeService;
    private final DictTranslate dictTranslate;

    private final VmsAvalibleTaxRateService vmsAvalibleTaxRateService;

    //新建一个01的常量
    private static final String ZERO_ONE = "01";
    private static final String ZERO_TWO = "02";
    //新建一个1000的常量

    private static final String ONE_THOUSAND = "1000";
    private static final String STR_N = "N";
    private static final String STR_Y = "Y";

    private static final String STR_05 = "05";
    private static final String STR_06 = "06";
    @Override
    public Result<IPage<VmsEpsInformationVo>> queryByPage(VmsEpsInformationQueryDto param) {
        //获取分页数据
        Integer pageNo = param.getPageNo();
        Integer pageSize = param.getPageSize();

        LambdaQueryWrapper<VmsEpsInformation> lq = new LambdaQueryWrapper<VmsEpsInformation>()
                .likeRight(StringUtil.isNotEmpty(param.getEpsCode()), VmsEpsInformation::getEpsCode, param.getEpsCode())
                .likeRight(StringUtil.isNotEmpty(param.getEpsName()), VmsEpsInformation::getEpsName, param.getEpsName())
                .likeRight(StringUtil.isNotEmpty(param.getGstcmCode()), VmsEpsInformation::getGstcmCode, param.getGstcmCode())
                .likeRight(StringUtil.isNotEmpty(param.getSphfwmc()), VmsEpsInformation::getSphfwmc, param.getSphfwmc())
                .orderByDesc(VmsEpsInformation::getCreatedTime);

        // 将数据库返回数据转换为VO返回前端
        IPage<VmsEpsInformationVo> page = page(new Page<>(pageNo, pageSize), lq)
                .convert(item -> {
                    VmsEpsInformationVo vo = new VmsEpsInformationVo();
                    // 转换数据
                    BeanUtils.copyBeanProp(vo, item);
                    if(ZERO_ONE.equals(item.getApplication())){
                        vo.setApplication("全部机构");
                    }else{
                        vo.setApplication("选定机构");
                    }
                    parseSlToString(item, vo, CommonConstant.STR_01,null);
                    return vo;
                });
        return Result.OK(page);
    }

    /**
     *
     * @param item
     * @param vo
     * @param type type=01表示查询企业商品信息，type=02表示查询企业服务信息给手工开票页面。以数据库保存的方式给
     */
    private void parseSlToString(VmsEpsInformation item, VmsEpsInformationVo vo,String type,VmsEpsUpdateInformationVo vo2) {
        //从itme中获取优惠政策标识，判断是否为免税或不征税，如果是，则将税率置为免税或不征税，否则，
        //将税率乘以100，并拼接上%，赋值到vo中
        String yhzcbs = item.getYhzcbs();
        BigDecimal rate = item.getZzssl();
        if(yhzcbs != null){
            if (CommonConstant.STR_01.equals(type)) {
                if ("03".equals(yhzcbs)) {
                    if (vo!=null) {
                        vo.setZzssl("免税");
                    }else
                    if(vo2 != null){
                       vo2.setZzssl("免税");
                    }
                } else if ("04".equals(yhzcbs)) {
                    if (vo!=null) {
                        vo.setZzssl("不征税");
                    }else
                    if(vo2 != null){
                        vo2.setZzssl("不征税");
                    }
                } else {
                    //将税率乘以100，并拼接上%，赋值到vo中
                    //将rate变为整数，后边没有多余的 .00
                    rate = rate.multiply(new BigDecimal(CommonConstant.STR_100)).stripTrailingZeros();
                    if (vo!=null) {
                        vo.setZzssl(rate + "%");
                    }else if(vo2 != null){
                        vo2.setZzssl(rate + "%");
                    }
                }
            } else if (CommonConstant.STR_02.equals(type)) {
                vo.setZzssl(rate.stripTrailingZeros().toString());
            }
        }else{
            if (CommonConstant.STR_01.equals(type)) {
                //这里有个问题，如果优惠标识为空，但是根据税收分类编码选择的数据，税率拆分后即有免税又有不征税，保存的时候都是0，
                //我怎么区分哪个是不征税或者免税
                rate = rate.multiply(new BigDecimal(CommonConstant.STR_100)).stripTrailingZeros();
                if(vo!=null) {
                    if(rate.compareTo(BigDecimal.ZERO)==0){
                        vo.setZzssl("免税");
                    }else{
                        //将税率乘以100，并拼接上%，赋值到vo中
                        vo.setZzssl(rate + "%");
                    }
                }else if(vo2 != null){
                    if(rate.compareTo(BigDecimal.ZERO)==0){
                        vo2.setZzssl("免税");
                    }else{
                        //将税率乘以100，并拼接上%，赋值到vo中
                        vo2.setZzssl(rate + "%");
                    }

                }
            } else if (CommonConstant.STR_02.equals(type)) {
                vo.setZzssl(rate.stripTrailingZeros().toString());
            }
        }
    }

    @Override
    public Result<IPage<VmsEpsInformationVo>> queryForHandleByPage(VmsEpsInformationQueryDto param) {
        // dto增加三个字段。一个cezs、发票类型、特定要素；增加差额征税编码表的实时验证;

        // 获得当前时间，转化为 yyyy-mm-dd
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDate = LocalDate.now().format(formatter);
        //获取分页数据
        Integer pageNo = param.getPageNo();
        Integer pageSize = param.getPageSize();
        //如果是差额征税
        if (StringUtil.isNotEmpty(param.getCezs())){
            if(param.getFpzl()!=null && StringUtil.isNotEmpty(param.getFpzl())){

                Page<VmsEpsInformation> pages = new Page<>(pageNo, pageSize);
                param.setJyjg(SecurityUtils.getDeptCode());
                param.setSystemDate(currentDate);
                IPage<VmsEpsInformation> vmsEpsInformationIPage = this.baseMapper.queryByPage(pages, param);
                IPage<VmsEpsInformationVo> page =vmsEpsInformationIPage.convert(item -> {
                    VmsEpsInformationVo vo = new VmsEpsInformationVo();
                    // 转换数据
                    BeanUtils.copyBeanProp(vo, item);
                    parseSlToString(item, vo, CommonConstant.STR_02,null);
                    return vo;
                });
                return Result.OK(page);
            }else{
                throw new BusinessException("7000","差额征税请输入发票类型");
            }
        }else{
            //非差额，逻辑不变
        LambdaQueryWrapper<VmsEpsInformation> lq = new LambdaQueryWrapper<VmsEpsInformation>()

                .apply(" TO_CHAR(qyrq, 'yyyy-MM-dd') <={0} ", currentDate )
                .apply(" TO_CHAR(tyrq, 'yyyy-MM-dd') >={0} ", currentDate)


                .likeRight(StringUtil.isNotEmpty(param.getEpsCode()), VmsEpsInformation::getEpsCode, param.getEpsCode())
                .likeRight(StringUtil.isNotEmpty(param.getEpsName()), VmsEpsInformation::getEpsName, param.getEpsName())
                .likeRight(StringUtil.isNotEmpty(param.getGstcmCode()), VmsEpsInformation::getGstcmCode, param.getGstcmCode())
                .likeRight(StringUtil.isNotEmpty(param.getSphfwmc()), VmsEpsInformation::getSphfwfljc, param.getSphfwmc())
                // 下边代码加上括号
                .and(i -> i.nested(j -> j.eq(VmsEpsInformation:: getApplication, CommonConstant.STR_02)
                        .like(VmsEpsInformation:: getJyjg, SecurityUtils.getDeptCode()))
                .or()
                .eq(VmsEpsInformation:: getApplication, CommonConstant.STR_01));
                if(StringUtil.isNotEmpty(param.getTdyslxdm())){

                    lq.eq(VmsEpsInformation::getTdyslxdm , param.getTdyslxdm());
                }else{
                    lq.apply("tdyslxdm is null ");
                }
                lq.eq(VmsEpsInformation::getCezs , CommonConstant.STR_02.equals(param.getCezs())?CommonConstant.STR_Y:CommonConstant.STR_N);//获取特定要素

        // 将数据库返回数据转换为VO返回前端
        IPage<VmsEpsInformationVo> page = page(new Page<>(pageNo, pageSize), lq)
                .convert(item -> {
                    VmsEpsInformationVo vo = new VmsEpsInformationVo();
                    // 转换数据
                    BeanUtils.copyBeanProp(vo, item);
                    parseSlToString(item, vo, CommonConstant.STR_02,null);
                    return vo;
                });
            return Result.OK(page);
        }

        //return Result.OK(page);
    }


    @Override
    public Result queryById(Long id) {
        //使用mybatisplus，根据ID查询数据
        VmsEpsInformation info = getById(id);
        if (info == null) {
            return Result.ERROR("数据不存在");
        }
        String application = info.getApplication();
        String jyjgArr = info.getJyjg();
        //商品和服务税收分类合并编码
        String gstcmCode = info.getGstcmCode();
        LambdaQueryWrapper<VmsClassifyCode> lq = new LambdaQueryWrapper<VmsClassifyCode>();
        lq.eq(VmsClassifyCode::getSphfwssflhbbm, gstcmCode);
        if (StringUtil.isNotEmpty(application)) {
            if (ZERO_ONE.equals(application)) {
                lq.eq(VmsClassifyCode::getDeptCode, ONE_THOUSAND);
            } else if (ZERO_TWO.equals(application)) {
                if (StringUtil.isNotEmpty(jyjgArr)) {
                    // 查询机构代码，进行查询
                    List<String> list = Arrays.asList(jyjgArr.split(","));
                    lq.in(VmsClassifyCode::getDeptCode, list);
                }
            }

        }
        VmsEpsUpdateInformationVo vo = new VmsEpsUpdateInformationVo();
        BeanUtils.copyBeanProp(vo, info);
        parseSlToString(info, null, CommonConstant.STR_01, vo);
        VmsClassifyCode one = classifyCodeService.getOne(lq, false);
        if(one!=null){
            vo.setKyslqyrq(one.getQyrq());
            vo.setKysltyrq(one.getTyrq());
            vo.setOptions(one.getZzssl());
            vo.setTdyslxdm(one.getTdyslxdm());
        }
        /**
         * 获取差额征税税率
         */
        LambdaQueryWrapper<VmsDifferentialCode> lq2 = new LambdaQueryWrapper<VmsDifferentialCode>();
        lq2.eq(VmsDifferentialCode::getSphfwssflhbbm,gstcmCode);
        if (StringUtil.isNotEmpty(application)) {
            if (ZERO_ONE.equals(application)) {
                lq2.eq(VmsDifferentialCode::getDeptCode, ONE_THOUSAND);
            } else if (ZERO_TWO.equals(application)) {
                if (StringUtil.isNotEmpty(jyjgArr)) {
                    // 查询机构代码，进行查询
                    List<String> list = Arrays.asList(jyjgArr.split(","));
                    lq2.in(VmsDifferentialCode::getDeptCode, list);
                }
            }

        }
        VmsDifferentialCode vmsDifferentialCode = differentialCodeService.getOne(lq2,false);
        if(vmsDifferentialCode!=null){
            vo.setCezssl(vmsDifferentialCode.getYbnsrsl());
        }
        return Result.OK(vo);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result insert(VmsEpsInformationDto vmsEpsInformation) {
        boolean b = this.insertOrUpdate(vmsEpsInformation.getCezs(), vmsEpsInformation.getGstcmCode(),vmsEpsInformation.getApplication(),vmsEpsInformation.getJyjg());
        if(!b){
            return Result.ERROR("该商品和服务税收分类合并编码在“差额征税编码信息表”中不存在，请核实!");
        }
        if(STR_N.equals(vmsEpsInformation.getCezs())){
            boolean b1 = this.checkGstcmCodetoClassifyCode(vmsEpsInformation.getGstcmCode(),
                    vmsEpsInformation.getApplication(),vmsEpsInformation.getJyjg());
            if(!b1){
                throw new BusinessException("7000","该商品和服务税收分类合并编码在“税收分类编码表表”中不存在，请核实!");
            }
        }
        if(!checkJldw(vmsEpsInformation.getTdyslxdm(),vmsEpsInformation.getJldw())){
            throw new BusinessException("7000","请选择计量单位!");
        }
        VmsEpsInformation one = getOne(new LambdaQueryWrapper<VmsEpsInformation>()
                .eq(VmsEpsInformation::getEpsCode, vmsEpsInformation.getEpsCode()), false);
        if(one!=null){
            return Result.ERROR("本系统内已存在重复的企业商品及服务编码！");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(CommonConstant.DATE_FORMAT_8);
            VmsEpsInformation info = new VmsEpsInformation();
        BeanUtils.copyBeanProp(info, vmsEpsInformation);
        Date now = new Date();
        info.setCreatedBy(SecurityUtils.getUserCode());
        info.setCreatedTime(now);
        info.setUpdatedBy(SecurityUtils.getUserCode());
        info.setUpdatedTime(now);
        try {
            Date qyrq = dateFormat.parse(vmsEpsInformation.getQyrq());
            Date tyrq = dateFormat.parse(vmsEpsInformation.getTyrq());
            info.setQyrq(qyrq);
            info.setTyrq(tyrq);
            parseSl(vmsEpsInformation, info);
            //拿出info转化后的税率，去可用税率验证是否存在，存在即返回成果，不存在及返回错误信息
            boolean rate = this.checkavalibleRate(info.getZzssl(),vmsEpsInformation.getApplication(),vmsEpsInformation.getJyjg());
            if (!rate) {
                return Result.ERROR("税率在可用税率表中不存在！");
            }
        } catch (ParseException e) {
            return Result.ERROR(e.getMessage());
        }

        return Result.OK(this.save(info));
    }

    private void parseSl(VmsEpsInformationDto vmsEpsInformation, VmsEpsInformation info) {
        //如果税率是字符串免税或者不征税，则直接保存0
        if("免税".equals(vmsEpsInformation.getZzssl()) || "不征税".equals(vmsEpsInformation.getZzssl())){
            info.setZzssl(new BigDecimal(CommonConstant.STR_0));
        }else {
            //保存的时候转换一下税率，页面选择的是字符串 3% 将其转换为 0.03保存到数据库中，使用bigdecimal
            String[] split = vmsEpsInformation.getZzssl().split("%");
            BigDecimal bigDecimal = new BigDecimal(split[0]);
            BigDecimal divide = bigDecimal.divide(new BigDecimal(CommonConstant.STR_100));
            info.setZzssl(divide);
        }
    }

    private boolean checkavalibleRate(BigDecimal sl,String application,String jyjg) {
        LambdaQueryWrapper<VmsAvalibleTaxRate> lq = new LambdaQueryWrapper<VmsAvalibleTaxRate>();
        lq.eq(VmsAvalibleTaxRate::getSlzsl, sl)
                .eq(VmsAvalibleTaxRate::getCszt,CommonConstant.STR_0);
        if (StringUtil.isNotEmpty(application)) {
            if (ZERO_ONE.equals(application)) {
                lq.eq(VmsAvalibleTaxRate::getDeptCode, ONE_THOUSAND);
            } else if (ZERO_TWO.equals(application)) {
                if (StringUtil.isNotEmpty(jyjg)) {
                    // 查询机构代码，进行查询
                    List<String> list = Arrays.asList(jyjg.split(","));
                    lq.in(VmsAvalibleTaxRate::getDeptCode, list);
                }
            }

        }
        VmsAvalibleTaxRate one = vmsAvalibleTaxRateService.getOne(lq, false);
        if (one == null) {
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result update(VmsEpsInformationDto vmsEpsInformation) {
        boolean b = this.insertOrUpdate(vmsEpsInformation.getCezs(), vmsEpsInformation.getGstcmCode(),vmsEpsInformation.getApplication(),vmsEpsInformation.getJyjg());
        if(!b){
            return Result.ERROR("该商品和服务税收分类合并编码在“差额征税编码信息表”中不存在，请核实!");
        }
        if(STR_N.equals(vmsEpsInformation.getCezs())){
            boolean b1 = this.checkGstcmCodetoClassifyCode(vmsEpsInformation.getGstcmCode(),
                    vmsEpsInformation.getApplication(),vmsEpsInformation.getJyjg());
            if(!b1){
                throw new BusinessException("7000","该商品和服务税收分类合并编码在“税收分类编码表表”中不存在，请核实!");
            }
        }
        if(!checkJldw(vmsEpsInformation.getTdyslxdm(),vmsEpsInformation.getJldw())){
            throw new BusinessException("7000","请选择计量单位!");
        }
        LambdaQueryWrapper<VmsEpsInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtil.isNotEmpty( vmsEpsInformation.getEpsCode()),VmsEpsInformation::getEpsCode,  vmsEpsInformation.getEpsCode());
        List<VmsEpsInformation> classifyCodeList = this.list(queryWrapper);
        if(classifyCodeList!=null &&classifyCodeList.size()>1){
            return Result.ERROR("本系统内已存在重复的企业商品及服务编码！");
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(CommonConstant.DATE_FORMAT_8);
        VmsEpsInformation info = new VmsEpsInformation();

        BeanUtils.copyBeanProp(info, vmsEpsInformation);
        try {
            Date qyrq = dateFormat.parse(vmsEpsInformation.getQyrq());
            Date tyrq = dateFormat.parse(vmsEpsInformation.getTyrq());
            info.setQyrq(qyrq);
            info.setTyrq(tyrq);
            parseSl(vmsEpsInformation, info);
            //拿出info转化后的税率，去可用税率验证是否存在，存在即返回成果，不存在及返回错误信息
            boolean rate = this.checkavalibleRate(info.getZzssl(),
                    vmsEpsInformation.getApplication(),vmsEpsInformation.getJyjg());
            if (!rate) {
                return Result.ERROR("税率在可用税率表中不存在！");
            }
        } catch (ParseException e) {
            return Result.ERROR(e.getMessage());
        }
        Date now = new Date();
        info.setUpdatedBy(SecurityUtils.getUserCode());
        info.setUpdatedTime(now);
        try {
            return Result.OK(this.updateById(info));
        }catch (Exception e){
            throw new BusinessException("7000","本系统内已存在重复的企业商品及服务编码！");
        }

    }

    @Override
    public VmsEpsInformation getInfoBySlv(String slv) {
        return getOne(new LambdaQueryWrapper<VmsEpsInformation>()
            .eq(VmsEpsInformation::getEpsCode, slv)
            .and(q -> {
                q.eq(VmsEpsInformation::getApplication, "01")
                        .or().like(VmsEpsInformation::getJyjg, SecurityUtils.getDeptCode());
            }), false);
    }

    @Override
    public VmsEpsInformation getInfoBySlvJyjg(String slv, String jyjg) {
        return getOne(new LambdaQueryWrapper<VmsEpsInformation>()
                .eq(VmsEpsInformation::getEpsCode, slv)
                .and(q -> {
                    q.eq(VmsEpsInformation::getApplication, "01")
                            .or().like(VmsEpsInformation::getJyjg, jyjg);
                }), false);
    }

    @Override
    public Result<IPage<VmsClassifyCodeForEpsPageVOList>> getClassCodePage(VmsEpsClassifyCodePageDto dto) {
        // 根据选择的机构范围，以及机构代码，来查询对应机构的商品服务编码，可能需要使用mapper，写出对应的sql
        Integer pageNo = dto.getPageNo();
        Integer pageSize = dto.getPageSize();
        // 创建返回对象

        // 获取税收分类编码页面，根据页面传递的交易机构
        //对于应用范围进行判断
        // 获得最近一次查询结果 - 首次页面加载查询
        LambdaQueryWrapper<VmsClassifyCode> lq = new LambdaQueryWrapper<VmsClassifyCode>()
                .eq(StringUtil.isNotEmpty(dto.getSphfwssflhbbm()), VmsClassifyCode::getSphfwssflhbbm, dto.getSphfwssflhbbm())
                .eq(StringUtil.isNotEmpty(dto.getSphfwmc()), VmsClassifyCode::getSphfwmc, dto.getSphfwmc())
                .eq(StringUtil.isNotEmpty(dto.getSphfwfljc()), VmsClassifyCode::getSphfwfljc, dto.getSphfwfljc())
                //VmsClassifyCode::getSfhzx不等于Y
                .ne(VmsClassifyCode::getSfhzx,STR_Y);

        String application = dto.getApplication();
        String jyjgArr = dto.getJyjgArr();

        if (StringUtil.isNotEmpty(application)) {
            if (CommonConstant.STR_01.equals(application)) {
                lq.eq(VmsClassifyCode::getDeptCode, CommonConstant.STR_1000);
            } else if (CommonConstant.STR_02.equals(application)) {
                if (StringUtil.isNotEmpty(jyjgArr)) {
                    // 查询机构代码，进行查询
                    List<String> list = Arrays.asList(jyjgArr.split(","));
                    lq.in(VmsClassifyCode::getDeptCode, list);
                }
            }

        }
        lq.orderByDesc(VmsClassifyCode::getId);

        IPage<VmsClassifyCodeForEpsPageVOList> page =classifyCodeService.page(new Page<>(pageNo, pageSize), lq).convert(item -> {
            VmsClassifyCodeForEpsPageVOList vo = new VmsClassifyCodeForEpsPageVOList();
            BeanUtils.copyBeanProp(vo, item);
            return vo;
        });
        return Result.OK(page);
    }

    @Override
    public Result checkGstcmCode(VmsEpsCheckDto param) {

        String gstcmCode=param.getGstcmCode();
        String application = param.getApplication();
        String jyjgArr = param.getJyjgArr();
        VmsEpsSlVo vmsEpsSlVo = new VmsEpsSlVo();
        /**
         * 获取税收分类编码的税率
         */
        LambdaQueryWrapper<VmsClassifyCode> lq2 = new LambdaQueryWrapper<VmsClassifyCode>();
        lq2.eq(VmsClassifyCode::getSphfwssflhbbm, gstcmCode);
        if (StringUtil.isNotEmpty(application)) {
            if (ZERO_ONE.equals(application)) {
                lq2.eq(VmsClassifyCode::getDeptCode, ONE_THOUSAND);
            } else if (ZERO_TWO.equals(application)) {
                if (StringUtil.isNotEmpty(jyjgArr)) {
                    // 查询机构代码，进行查询
                    List<String> list2 = Arrays.asList(jyjgArr.split(","));
                    lq2.in(VmsClassifyCode::getDeptCode, list2);
                }
            }

        }
        List<VmsClassifyCode> list2 = classifyCodeService.list(lq2);
        if(!CollectionUtils.isAnyEmpty(list2)){
            VmsClassifyCode vmsClassifyCode = list2.get(0);
            vmsEpsSlVo.setZzssl(vmsClassifyCode.getZzssl());
            if(CommonConstant.STR_Y.equals(vmsClassifyCode.getCezs())){
                LambdaQueryWrapper<VmsDifferentialCode> lq = new LambdaQueryWrapper<VmsDifferentialCode>();
                lq.eq(VmsDifferentialCode::getSphfwssflhbbm,gstcmCode);
                if (StringUtil.isNotEmpty(application)) {
                    if (ZERO_ONE.equals(application)) {
                        lq.eq(VmsDifferentialCode::getDeptCode, ONE_THOUSAND);
                    } else if (ZERO_TWO.equals(application)) {
                        if (StringUtil.isNotEmpty(jyjgArr)) {
                            // 查询机构代码，进行查询
                            List<String> list = Arrays.asList(jyjgArr.split(","));
                            lq.in(VmsDifferentialCode::getDeptCode, list);
                        }
                    }

                }
                List<VmsDifferentialCode> list = differentialCodeService.list(lq);

                if(!CollectionUtils.isAnyEmpty(list)) {
                    VmsDifferentialCode vmsDifferentialCode = list.get(0);
                    vmsEpsSlVo.setCezsssl(vmsDifferentialCode.getYbnsrsl());
                }else{
                    return Result.ERROR("该商品和服务税收分类合并编码在“差额征税编码信息表”中不存在，请核实!");
                }
            }
        }else{
            return Result.ERROR("税后分类编码数据为空");
        }


        return Result.OK(vmsEpsSlVo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteById(Long id) {
        boolean b = removeById(id);
        if (b){
            return Result.OK();
        }
        return Result.ERROR("删除失败");
    }

    /**
     * 查验差额征税表是否有数据
     * @param cezs
     * @param gstcmCode
     * @param application
     * @param jyjgArr
     * @return
     */
    private boolean insertOrUpdate(String cezs,String gstcmCode,String application,String jyjgArr) {
        if (CommonConstant.STR_Y.equals(cezs)) {
            VmsEpsCheckDto dto =new VmsEpsCheckDto();
            dto.setGstcmCode(gstcmCode);
            dto.setApplication(application);
            dto.setJyjgArr(jyjgArr);
            Result result = this.checkGstcmCode(dto);
            if (CommonConstants.REST_SUCCESS.equals(result.getCode())) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 验证税收分类编码
     * @param gstcmCode
     * @return
     */
    private boolean checkGstcmCodetoClassifyCode(String gstcmCode,String application,String jyjgArr){
        LambdaQueryWrapper<VmsClassifyCode> lq = new LambdaQueryWrapper<VmsClassifyCode>();
        lq.eq(VmsClassifyCode::getSphfwssflhbbm, gstcmCode);
        if (StringUtil.isNotEmpty(application)) {
            if (ZERO_ONE.equals(application)) {
                lq.eq(VmsClassifyCode::getDeptCode, ONE_THOUSAND);
            } else if (ZERO_TWO.equals(application)) {
                if (StringUtil.isNotEmpty(jyjgArr)) {
                    // 查询机构代码，进行查询
                    List<String> list2 = Arrays.asList(jyjgArr.split(","));
                    lq.in(VmsClassifyCode::getDeptCode, list2);
                }
            }

        }
        VmsClassifyCode one = classifyCodeService.getOne(lq, false);
        if(one==null){
            return false;
        }
        return true;
    }
    /**
     * 验证计量单位
     * @param teysdm
     * @param jldw
     * @return
     */
    private boolean checkJldw(String teysdm,String jldw){
        if(STR_05.equals(teysdm) || STR_06.equals(teysdm)){
            if(StringUtil.isEmpty(jldw)){
                return false;
            }
        }
        return true;
    }
}
